package com.example.bcvicse.com.controller;

import com.example.bcvicse.com.config.ParamConfig;
import com.example.bcvicse.com.pojo.ResponseJSON;
import com.example.bcvicse.com.pojo.vo.CarData;
import com.example.bcvicse.com.service.ReceiveService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

@Controller
public class ReceiveController {

    @Resource
    ReceiveService receiveService;
    @ResponseBody
    @RequestMapping("/receive")
    public String receive(HttpServletRequest request) throws IOException {
        String command = request.getParameter("command");
        ObjectMapper mapper = new ObjectMapper();
        if(ParamConfig.COMMAND_A.equals(command)){
            String s = request.getParameter("param");
            CarData carData = mapper.readValue(s,CarData.class);
            System.out.println(carData);
            if("2".equals(carData.getState())){//A机构修改数据重新上传
                if(carData.getFee()>=0){
                    if(receiveService.addBData(carData)>0){
                        return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_TRUE,"1",new Date(),"修改上传成功"));
                    }
                }else {
                    return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_FALSE,"3",new Date(),"价格异常"));
                }
            }else if("1".equals(carData.getState())){//该数据已上传，禁止重复上传
                return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_FALSE,"1",new Date(),"请勿重复上传"));
            }else{
                if(!"3".equals(carData.getState())&&receiveService.selectById(carData.getId())){
                    return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_FALSE,"1",new Date(),"请勿重复上传"));
                }else{
                    if(carData.getFee()>=0){
                        if(receiveService.addBData(carData)>0){
                            return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_TRUE,"1",new Date(),"上传成功"));
                        }
                    }else {
                        return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_FALSE,"3",new Date(),"价格异常"));
                    }
                }
                return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_FALSE,"3",new Date(),"上传失败"));
            }
        }
        return mapper.writeValueAsString(new ResponseJSON(ParamConfig.RECEIVE_FALSE,"3",new Date(),"口令不对"));
    }
}
